import md5 from "../js_sdk/md5/md5";
export function editSign(obj) {
	const timp = new Date().getTime();
	const nonce = generateRandomString(32);
	//    const nonce = generateRandomString(32);
	let sign = "";
	sign = genSignParams(obj, timp, nonce);
	return {
		"X-Nonce": nonce,
		"X-Timestamp": timp,
		"X-Sign": sign,
	};
}

function genSignParams(obj, timp, nonce) {
	const inObject = Object.assign({}, obj);
	var sorter = function(inObject) {
		var sortedJson = {};
		var sortedKeys = Object.keys(inObject).sort();
		for (var i = 0; i < sortedKeys.length; i++) {
			console.log("sortedKeys[i]", sortedKeys[i]);
			sortedJson[sortedKeys[i]] = inObject[sortedKeys[i]];
		}
		return sortedJson;
	};
	var sortedParam = sorter(inObject);

	var needSignatureStr = "";

	needSignatureStr = convertObjectToQueryString(sortedParam);
	const secretKey = "WQBymFuoi5okgiODmLSCbSIvT2PQla8ctWJxkDH7PEqBmfZmnTu8zeFRS4jAo7";




	if (needSignatureStr) {
		needSignatureStr += `&timestamp=${timp}&nonce=${nonce}&secret=${secretKey}`;
		return md5(needSignatureStr).toString().toUpperCase();
	} else {
		needSignatureStr = `timestamp=${timp}&nonce=${nonce}&secret=${secretKey}`
		return md5(needSignatureStr).toString().toUpperCase();
	}
}

function convertObjectToQueryString(obj) {
	const isNotNull = val => val !== null && val !== undefined && val !== ''

	const processValue = (value) => {
		if (typeof value === 'string') {
			return value.startsWith('https://') ? '' : value;
		} else if (Array.isArray(value)) {
			return `[${value.map(item => processValue(item)).filter(isNotNull).join(', ')}]`;
		} else if (typeof value === 'object' && value !== null) {
			const entries = Object.entries(value)
				.map(([k, v]) => `${k}=${processValue(v)}`)
				.filter(isNotNull);
			return `{${entries.join(', ')}}`;
		} else if (typeof value === 'number') {
			return value;
		}
		return '';
	};

	const entries = Object.entries(obj)
		.map(([key, value]) => {
			const processed = processValue(value);
			return isNotNull(processed) ? `${key}=${processed}` : null;
		})
		.filter(isNotNull);

	return entries.join('&');
}

function generateRandomString(length) {
	const charset =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	let result = "";
	for (let i = 0; i < length; i++) {
		const randomChar = charset[Math.floor(Math.random() * charset.length)];
		result += randomChar;
	}
	return result;
}